package io.guanghe.gmall.product.exception;

import io.guanghe.common.exception.BizException;
import io.guanghe.common.exception.ExceptionCodeEnum;
import io.guanghe.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "io.guanghe.gmall.product.controller")
public class WebExceptionHandler {

    @ExceptionHandler(BizException.class)
    public R handlerNoFoundException(BizException e) {
        ExceptionCodeEnum exceptionCodeEnum = e.getExceptionCodeEnum();
        log.error(exceptionCodeEnum.getMsg(), e);
        return R.result(exceptionCodeEnum);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        //获取校验结果
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item -> {
            errorMap.put(item.getField(), item.getDefaultMessage());
        });
        log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());
        return R.error(-1, "数据不合法").put("data", errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        return R.error(throwable.getMessage());
    }
}
